package com.z.xhelper.core.listener;

import static com.z.xhelper.core.utils.HelperUtil.beanToJsonString;
import static com.z.xhelper.core.utils.HelperUtil.hookSendTextMsg;

import com.z.xhelper.core.config.BeanContainer;
import com.z.xhelper.core.dao.WeChatMsg;
import com.z.xhelper.core.eventbus.IListener;
import com.z.xhelper.core.events.MsgReceiveEvent;
import com.z.xhelper.core.socket.WebSocket;

import java.util.HashMap;
import java.util.Objects;

/**
 * 文本消息监听器
 */
public class TextMsgReceiveListener implements IListener<MsgReceiveEvent> {
    private static HashMap<String,String> msgMap = new HashMap<>();
    @Override
    public Class<?> getEventName() {
        return MsgReceiveEvent.class;
    }

    @Override
    public void run(MsgReceiveEvent event) {
        WeChatMsg context = event.getContext();

        if (context.getType() != 1){
            return;
        }
        // 过滤自己发送的消息
        if (context.getIsSend() == 1){
            return;
        }

        if (!isOnLine()){
            quickReplay("我的服务掉线了，帮我找我爸爸。",context.getTalker());
            return;
        }

        if (isCheckOnline(context)){
            if (isOnLine()){
                quickReplay("我在线的",context.getTalker());
                return;
            }
            quickReplay("我掉线了",context.getTalker());
            return;
        }

        if (isRepeat(context)){
            quickReplay("请勿重复发送",context.getTalker());
            return;
        }
        // 处理文本消息
        Objects.requireNonNull(BeanContainer.getBean(WebSocket.class))
                .send(beanToJsonString(context));
    }

    private static void quickReplay(String content, String talker) {
        WeChatMsg msg = new WeChatMsg();
        msg.setContent(content);
        msg.setTalker(talker);
        hookSendTextMsg(msg);
    }

    public boolean isRepeat(WeChatMsg context) {
        if(msgMap.containsKey(context.getTalker()) && Objects.equals(msgMap.get(context.getTalker()), context.getContent())){
            return true;
        }
        msgMap.put(context.getTalker(),context.getContent());
        return false;
    }
    public boolean isCheckOnline(WeChatMsg context) {
        if(context.getContent().contains("在吗") || context.getContent().contains("在线")
                || context.getContent().contains("在么")){
            return true;
        }
        return false;
    }

    public boolean isOnLine() {
        return Objects.requireNonNull(BeanContainer.getBean(WebSocket.class)).isOnline();
    }


}
